import axios from 'axios'

import { getToken, clearToken } from './token'
import { history } from './history'

const http = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000
})

http.interceptors.request.use(config => {
  // token
  config.headers.Authorization = `Bearer ${getToken()}`
  return config
})

http.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response.status === 401) {
      clearToken()
      history.push('/login')
    }
  }
)

export { http }
